﻿using System;
using System.Text;
using System.IO;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;

using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

using System.Text.RegularExpressions;


namespace CMSE.Extensions.Vimeo.UserControls
{
    public class VimeoAdder : UserControl
    {
        private const string HEADER = "<%@ Register Tagprefix=\"SharePoint\" Namespace=\"Microsoft.SharePoint.WebControls\" Assembly=\"Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" %>";
        private const string NEW_HEADER = @"<%@ Assembly Name='Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' %>
                <%@ Register TagPrefix='SharePoint' Namespace='Microsoft.SharePoint.WebControls' Assembly='Microsoft.SharePoint' %>
                <%@ Import Namespace='System.IO' %>
                <%@ Import Namespace='Microsoft.SharePoint' %>
                <%@ Import Namespace='Microsoft.SharePoint.Utilities' %>
                <%@ Import Namespace='Microsoft.SharePoint.WebControls' %>";

        private const string FOOTER = "</head>";
        private const string NEW_FOOTER = @"<body>
                <form id='Form1' runat='server'>
                <SharePoint:UrlRedirector id='Redirector1' runat='server' />
                </form>
                </body>
                </html>";

        private TextBox _tbVimeoUrl = new TextBox();

        private Literal _litVimeoPreview = new Literal();

        // Label - 
        private Label _lblVimeoLabel = new Label();
        private Label _lblDebug = new Label();

        private Button _btnOk = new Button();


        public VimeoAdder() { }

        protected override void CreateChildControls()
        {
            _btnOk.Text = "Add video";
            _btnOk.Click += new EventHandler(_btnOk_Click);

            _lblVimeoLabel.Text = "Enter the URL the Vimeo Video here:";
            _lblVimeoLabel.CssClass = "cmse-label";

            _tbVimeoUrl.CssClass = "cmse-vimeourl";

            _litVimeoPreview.Text = "<div id='cmse-youtube-preview'></div>";

            this.Controls.Add(_lblVimeoLabel);
            this.Controls.Add(_tbVimeoUrl);
            this.Controls.Add(_btnOk);
            this.Controls.Add(_litVimeoPreview);
            this.Controls.Add(_lblDebug);

        }

        void _btnOk_Click(object sender, EventArgs e)
        {

            NameValueCollection queryString = Request.QueryString;
            if (queryString["List"] != null)
            {
                using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        if (queryString["List"] == null)
                        {
                            // TODO: throw an error                            
                            return;
                        }
                        Guid listGuid = new Guid(queryString["List"]);
                        SPList list = web.Lists[listGuid];
                        SPDocumentLibrary docLib = list as SPDocumentLibrary;

                        if (list != null)
                        {

                            InformationExtractor extractor = new InformationExtractor();
                            string info = extractor.GetInformationStream(_tbVimeoUrl.Text);
                            VimeoVideo video = extractor.GetInformation(new Uri(_tbVimeoUrl.Text));

                            string filename = NormalizeFilename(video.Title);
                            SPFile file = docLib.RootFolder.Files.Add(filename, new byte[0]);


                            if (queryString["ContentTypeId"] != null)
                            {
                                file.Properties["ContentTypeId"] = queryString["ContentTypeId"];
                            }

                            SPFieldUrlValue fieldUrlValue = new SPFieldUrlValue();
                            fieldUrlValue.Url = _tbVimeoUrl.Text;
                            fieldUrlValue.Description = _tbVimeoUrl.Text;

                            file.Properties["URL"] = fieldUrlValue.ToString();
                            file.Update();

                            if (file != null)
                            {
                                byte[] byteArray = file.OpenBinary();
                                using (MemoryStream mem = new MemoryStream())
                                {
                                    mem.Write(byteArray, 0, (int)byteArray.Length);

                                    string content = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
                                    content = content.Replace(HEADER, NEW_HEADER);
                                    content = content.Replace(FOOTER, NEW_FOOTER);

                                    file.SaveBinary(Encoding.ASCII.GetBytes(content));

                                }
                            }
                            SPListItem item = file.Item;
                            item[SPBuiltInFieldId.AlternateThumbnailUrl] = video.ThumbnailLarge;
                            SPFieldUrlValue urlValue = new SPFieldUrlValue();
                            urlValue.Url = _tbVimeoUrl.Text;
                            urlValue.Description = filename.Replace(".aspx", "");
                            item[SPBuiltInFieldId.URL] = urlValue.ToString();
                            item[SPBuiltInFieldId.Title] = video.Title;

                            // Getting length field
                                                        // Getting length field
                            if (web.Fields.GetFieldByInternalName("MediaLengthInSeconds") != null)
                            {
                                SPField mediaLength = web.Fields.GetFieldByInternalName("MediaLengthInSeconds");
                                item[mediaLength.Title] = video.Duration;
                            }

                            // Description
                            item[SPBuiltInFieldId._Comments] = video.Description;
                            item[SPBuiltInFieldId.Keywords] = video.Keywords;
                            item[SPBuiltInFieldId._Author] = video.Uploader;
                            item.SystemUpdate(false);
                            web.AllowUnsafeUpdates = false;

                            string redirectUrl = list.DefaultEditFormUrl + "?ID=" + item.ID + "&Source=" + queryString["Source"];
                            Response.Redirect(redirectUrl);

                        }

                    }
                }
            }
        }

        private string NormalizeFilename(string oldFilename)
        {
            string newFileName = Regex.Replace(oldFilename, @"[?:\/*""<>|]", "");
            if (newFileName.Length > 255)
            {
                return newFileName.Substring(0, 249);
            }
            if (newFileName.EndsWith("."))
            {
                newFileName = newFileName.Substring(0, newFileName.Length - 1);
            }
            return newFileName.Replace("..", ".") + ".aspx";

        }
    }
}
